package com.keifo.final2.controller;

import com.keifo.final2.entity.TeamMember;
import com.keifo.final2.service.TeamMemberService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/team")
public class TeamMemberController {

    @Autowired
    private TeamMemberService teamMemberService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String username, @RequestParam String password, HttpServletResponse response) {
        Map<String, Object> responseMap = new HashMap<>();

        if (teamMemberService.validateLogin(username, password)) {
            // 登录成功
            responseMap.put("success", true);
            responseMap.put("message", "登录成功");

        } else {
            // 登录失败
            responseMap.put("success", false);
            responseMap.put("message", "登录失败，用户不存在或密码错误");
        }

        return responseMap;
    }

    @GetMapping("/members")
    public List<TeamMember> getAllMembers() {
        return teamMemberService.getAllMembers();
    }

    @PostMapping("/add")
    public Map<String, Object> addMember(@RequestBody TeamMember member) {
        teamMemberService.addMember(member);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "添加成功");
        return response;
    }

    @PutMapping("/update")
    public Map<String, Object> updateMember(@RequestBody TeamMember member) {
        teamMemberService.updateMember(member);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "更新成功");
        return response;
    }

    @GetMapping("/getMember")
    public TeamMember getMember(@RequestParam("username") String username) {
        return teamMemberService.getMemberByUsername(username) == null ? new TeamMember() : teamMemberService.getMemberByUsername(username);
    }

    @DeleteMapping("/delete/{username}")
    public Map<String, Object> deleteMember(@PathVariable String username) {
        teamMemberService.deleteMember(username);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "删除成功");
        return response;
    }
}